//
//  PlaceViewController.m
//  舟航007机车卫士
//
//  Created by admin on 15/11/9.
//  Copyright (c) 2015年 redoor. All rights reserved.
//

#import "PlaceViewController.h"
#import <BaiduMapAPI_Map/BMKPinAnnotationView.h>
#import "newButton.h"
#import "RemarkButton.h"
#import <BaiduMapAPI_Search/BMKGeocodeSearchOption.h>
#import "PopMsg.h"
#import "PopLoadMsg.h"
#import "myButton.h"
#import <BaiduMapAPI_Map/BMKAnnotation.h>
#import <BaiduMapAPI_Search/BMKRouteSearchOption.h>
#import "AlertView.h"
#import "LoginViewController.h"

#define MYBUNDLE_NAME @ "mapapi.bundle"
#define MYBUNDLE_PATH [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent: MYBUNDLE_NAME]
#define MYBUNDLE [NSBundle bundleWithPath: MYBUNDLE_PATH]
@interface PlaceViewController ()

{
    BMKRouteSearch *routeSearch;
    BMKGeoCodeSearch *search;
    BMKReverseGeoCodeOption *option;
    BMKMapView *mapView;
    BMKPointAnnotation *anni;
    BMKLocationService* _locService;
    UILabel *paopaoLab_time;
    UILabel *paopaoLab_phone;
    UILabel *paopaoLab_status;
    UILabel *paopaoLab_loc;
    UIWindow *window;
    UIButton *btn_enlarge;
    UIButton *btn_reduce;
    UIButton *btn_maptype;
    UIButton *btn_remarktype;
    UIImageView *paopao;
    // seconed paopao push window
    UIImageView *paopao2;
    BOOL start;
    BOOL end;
    BOOL start2;
    BOOL end2;
    NSTimer *timer;
    UIImageView *alertimage;
    UIView *backView;
    newButton *btn_weixing;
    newButton *btn_commen;
    RemarkButton *btn_guiji;
    RemarkButton *btn_maodian;
    BOOL back;
    
    PopLoadMsg *loadmsg;
    //设置点击不同button的不同状态，进行不同的操作
    NSInteger index;
    NSInteger tag_remark;
    UIView *datebackview;
    UIView *timebackview;
    UILabel *line;
    UIButton *btn_date;
    myButton *btn_totime;
    myButton *btn_fromtime;
    UIView *datepickerView;
    NSMutableArray *array_historyPositions;
    int count_start;
    int count_end;
    int count;
    UIButton *leftdate;
    UIButton *rightdate;
}
@property(nonatomic)UIDatePicker *datepicker;
@property(nonatomic)UIDatePicker *timepicker;
@property (nonatomic, strong) BMKPinAnnotationView *annotationView; // 设置大头针图片


@end

@interface RouteAnnotation : BMKPointAnnotation
{
    int _type; ///<0:起点 1：终点 2：公交 3：地铁 4:驾乘 5:途经点
    int _degree;
}

@property (nonatomic) int type;
@property (nonatomic) int degree;
@end

@implementation RouteAnnotation

@synthesize type = _type;
@synthesize degree = _degree;
@end



@implementation PlaceViewController
@synthesize datepicker,timepicker;


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.userOrTourist = [[NSUserDefaults standardUserDefaults] objectForKey:@"userOrTourist"];
    self.leftbtn.hidden=YES;
    routeSearch=[[BMKRouteSearch alloc]init];
    routeSearch.delegate=self;
    count_start=0;
    count_end=1;
    self.tabBarController.delegate=self;
    back=NO;
    index=1;
    tag_remark=0;
    loadmsg=[PopLoadMsg new];
    [self.centerbtn setTitle:@"实时位置" forState:UIControlStateNormal];
    [self.rightbtn setTitle:@"历史轨迹" forState:UIControlStateNormal];
    [self.rightbtn setImage:[UIImage imageNamed:@"top_icon02"] forState:UIControlStateNormal];
    [self.centerbtn addTarget:self action:@selector(tapped_location) forControlEvents:UIControlEventTouchUpInside];
    [self.rightbtn addTarget:self action:@selector(tapped_remark) forControlEvents:UIControlEventTouchUpInside];
    search=[[BMKGeoCodeSearch alloc]init];
    option=[[BMKReverseGeoCodeOption alloc]init];
    search.delegate=self;
    
    [self configview];

}



//实时位置
- (void)tapped_location{
    //点击实时位置
    if ([self.userOrTourist isEqualToString:@"1"]) {
        if(index==2 || index == 1){
            index=1;
            BMKCoordinateRegion region ;//表示范围的结构体
            region.center=mapView.centerCoordinate;
            region.span.latitudeDelta=0.01;
            region.span.longitudeDelta=0.01;
            mapView.region=region;
            
#pragma mark 进行实时定位设置

            [self dorequestForGetCurrentLoction];
            
            
            if (index == 2) {
          
            timer=[NSTimer scheduledTimerWithTimeInterval:reloadmaptime target:self selector:@selector(dorequestForGetCurrentLoction2) userInfo:nil repeats:YES];
                
            }
            
            
            anni=[[BMKPointAnnotation alloc]init];
                
            
            anni.coordinate=mapView.centerCoordinate;
            anni.title=@"qq";
            mapView.delegate=self;
            NSArray* array = [NSArray arrayWithArray:mapView.annotations];
            [mapView removeAnnotations:array];
            array = [NSArray arrayWithArray:mapView.overlays];
            [mapView removeOverlays:array];
            
            [mapView addAnnotation:anni];
        }
        
        btn_remarktype.hidden=YES;
        timebackview.hidden=YES;
        datebackview.hidden=YES;
        line.hidden=YES;
        [self.centerbtn setImage:[UIImage imageNamed:@"top_icon01"] forState:UIControlStateNormal];
        [self.rightbtn setImage:[UIImage imageNamed:@"top_icon02"] forState:UIControlStateNormal];

    }
    else {
        AlertView *alertView = [[AlertView alloc] initWithConfirmButtonBlock:^{
            NSLog(@"登录");
            LoginViewController *loginVC = [[LoginViewController alloc]init];
            [self presentViewController:loginVC animated:YES completion:nil];
        } cancelButtonBlock:^{
            NSLog(@"取消");
        }];
        [self.view addSubview:alertView];
    }
}

//历史轨迹查询
- (void)tapped_remark{
    //点击历史轨迹
    if ([self.userOrTourist isEqualToString:@"1"]) {
        if(index==1){
            [self dorequestForGetbicycleState];
        }
    }
    else {
        AlertView *alertView = [[AlertView alloc] initWithConfirmButtonBlock:^{
            NSLog(@"登录");
            LoginViewController *loginVC = [[LoginViewController alloc]init];
            [self presentViewController:loginVC animated:YES completion:nil];
        } cancelButtonBlock:^{
            NSLog(@"取消");
        }];
        [self.view addSubview:alertView];
    }
    
}

- (void)configview{
    //构建地图试图
    mapView=[[BMKMapView alloc]initWithFrame:CGRectMake(0, 20+44*H, SCREEN_WIDTH, SCREEN_HEIGHT-20-44*H)];
    anni=[[BMKPointAnnotation alloc]init];
   
    anni.coordinate=mapView.centerCoordinate;
    anni.title=@"qq";
    mapView.delegate=self;
    //[mapview addAnnotation:anni];
    BMKCoordinateRegion region ;//表示范围的结构体
    region.center=mapView.centerCoordinate;
    region.span.latitudeDelta=0.01;
    region.span.longitudeDelta=0.01;
    mapView.region=region;
    
    [self.view addSubview:mapView];
    window=[UIApplication sharedApplication].keyWindow;
//    构建地图的放大缩小
    btn_enlarge=[[UIButton alloc]initWithFrame:CGRectMake(10*W, SCREEN_HEIGHT-49-150*W, 30*W, 50*W)];
    [btn_enlarge setImage:[UIImage imageNamed:@"map_icon01"] forState:UIControlStateNormal];
    [btn_enlarge addTarget:self action:@selector(tapped_enlargemap) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn_enlarge];
    
    btn_reduce=[[UIButton alloc]initWithFrame:CGRectMake(10*W, SCREEN_HEIGHT-49-90*W, 30*W, 50*W)];
    [btn_reduce setImage:[UIImage imageNamed:@"map_icon02"] forState:UIControlStateNormal];
    [btn_reduce addTarget:self action:@selector(tapped_reducemap) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn_reduce];
    btn_maptype=[[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH-40*W, SCREEN_HEIGHT-49-140*W, 30*W, 30*W)];
    [btn_maptype setImage:[UIImage imageNamed:@"map_icon03"] forState:UIControlStateNormal];
    [btn_maptype addTarget:self action:@selector(tapped_changemaptype) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn_maptype];
    
    btn_remarktype=[[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH-40*W, SCREEN_HEIGHT-49-80*W, 30*W, 30*W)];
    [btn_remarktype setImage:[UIImage imageNamed:@"map_icon04"] forState:UIControlStateNormal];
    [btn_remarktype addTarget:self action:@selector(tapped_changeremarktype) forControlEvents:UIControlEventTouchUpInside];
    btn_remarktype.hidden=YES;
    [self.view addSubview:btn_remarktype];

    datebackview=[[UIView alloc]initWithFrame:CGRectMake(0, 20+44*H, SCREEN_WIDTH, 35*H)];
    datebackview.backgroundColor=[UIColor colorWithWhite:0.1 alpha:0.8];
//    datebackview.backgroundColor = [UIColor greenColor];
    
    [self.view addSubview:datebackview];
    line=[[UILabel alloc]initWithFrame:CGRectMake(0, 20+79*H, SCREEN_WIDTH, 1)];
    line.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:line];
    
    timebackview=[[UIView alloc]initWithFrame:CGRectMake(0, 20+80*H, SCREEN_WIDTH, 45*H)];
    timebackview.backgroundColor=[UIColor colorWithWhite:0.1 alpha:0.8];
    
//    timebackview.backgroundColor = [UIColor redColor];
    [self.view addSubview:timebackview];
    
    btn_date=[[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/3, 0, SCREEN_WIDTH/3, 35*H)];
    NSDate *date=[NSDate date];
    

    
    
    
    
    NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
//    data日期操作显示
    [btn_date addTarget:self action:@selector(tapped_selectDate) forControlEvents:UIControlEventTouchUpInside];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *str_date=[formatter stringFromDate:date];
    [btn_date setTitle:str_date forState:UIControlStateNormal];
    btn_date.backgroundColor=[UIColor clearColor];
    [btn_date setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    btn_date.titleLabel.font=[UIFont systemFontOfSize:14];
    btn_date.titleLabel.textAlignment=NSTextAlignmentCenter;
    [datebackview addSubview:btn_date];
//        btn_date.backgroundColor = [UIColor blueColor];
    
    leftdate=[[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/6, 10*H, 12*H, 15*H)];
    [leftdate addTarget:self action:@selector(tapped_reducedate) forControlEvents:UIControlEventTouchUpInside];
    [leftdate setImage:[UIImage imageNamed:@"map_leftarrow"] forState:UIControlStateNormal];
    [datebackview addSubview:leftdate];
//    leftdate.backgroundColor = [UIColor orangeColor];
    
    rightdate=[[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH*5/6-12*H, 10*H, 12*H, 15*H)];
    [rightdate addTarget:self action:@selector(tapped_recreasedate) forControlEvents:UIControlEventTouchUpInside];
    [rightdate setImage:[UIImage imageNamed:@"map_rightarrow"] forState:UIControlStateNormal];
    [datebackview addSubview:rightdate];
    UILabel *lab_to=[[UILabel alloc]initWithFrame:CGRectMake((SCREEN_WIDTH-10*W)/2, 0, 10*W, 45*H)];
    lab_to.textColor=[UIColor whiteColor];
    lab_to.text=@"~";
    [timebackview addSubview:lab_to];
    
    btn_fromtime=[[myButton alloc]initWithFrame:CGRectMake(80*W, 10*H, 60*W, 25*H)];
    [btn_fromtime setImage:[UIImage imageNamed:@"5pic_timebg"] forState:UIControlStateNormal];
    [btn_fromtime setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    btn_fromtime.titleLabel.font=[UIFont systemFontOfSize:14];
    btn_fromtime.titleLabel.textAlignment=NSTextAlignmentCenter;
    [btn_fromtime addTarget:self action:@selector(tapped_selectFromTime) forControlEvents:UIControlEventTouchUpInside];

    [timebackview addSubview:btn_fromtime];
    
    btn_totime=[[myButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH-60*W-80*W, 10*H, 60*W, 25*H)];
    [btn_totime setImage:[UIImage imageNamed:@"5pic_timebg"] forState:UIControlStateNormal];
    [btn_totime setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    btn_totime.titleLabel.font=[UIFont systemFontOfSize:14];
    btn_totime.titleLabel.textAlignment=NSTextAlignmentCenter;
    [timebackview addSubview:btn_totime];
    
    [formatter setDateFormat:@"HH:mm"];
    [btn_totime setTitle:[formatter stringFromDate:date] forState:UIControlStateNormal];
    [btn_totime addTarget:self action:@selector(tapped_selectToTime) forControlEvents:UIControlEventTouchUpInside];
    NSDate *fromedate=[NSDate dateWithTimeInterval:-60*60 sinceDate:date];
    [btn_fromtime setTitle:[formatter stringFromDate:fromedate] forState:UIControlStateNormal];
    datebackview.hidden=YES;
    timebackview.hidden=YES;
    line.hidden=YES;
    
}

#pragma mark - 日期和时间
- (void)tapped_selectToTime{
    self.tabBarController.tabBar.userInteractionEnabled=NO;
    //点击选择终止时间
    back=YES;
    backView=[[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    backView.backgroundColor=[UIColor colorWithWhite:0.2 alpha:0.5];
    [self.view addSubview:backView];
    
    btn_enlarge.enabled=NO;
    btn_reduce.enabled=NO;
    btn_remarktype.enabled=NO;
    btn_maptype.enabled=NO;
    datepickerView=[[UIView alloc]initWithFrame:CGRectMake(20*W, SCREEN_HEIGHT/4, SCREEN_WIDTH-40*W, SCREEN_HEIGHT/2)];
    datepickerView.backgroundColor=[UIColor whiteColor];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *str_date=btn_date.titleLabel.text;
    str_date=[str_date stringByAppendingString:@" "];
    str_date=[[str_date stringByAppendingString:btn_totime.titleLabel.text]stringByAppendingString:@":00"];
    NSDate *date = [dateFormatter dateFromString:str_date];
    
    [backView addSubview:datepickerView];
    timepicker=[[UIDatePicker alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH-40*W, SCREEN_HEIGHT/2)];
    timepicker.date=date;
    timepicker.datePickerMode=UIDatePickerModeTime;
    // datepicker.backgroundColor=[UIColor blackColor];
    timepicker.frame=CGRectMake(0, 0, SCREEN_WIDTH-40*W, SCREEN_HEIGHT/2-50);
    [datepickerView addSubview:timepicker];
    UIView *line1=[[UIView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT/2-50, SCREEN_WIDTH-40*W, 1)];
    line1.backgroundColor=[UIColor colorWithRed:(CGFloat)21/255 green:(CGFloat)124/255 blue:(CGFloat)244/255 alpha:1.0];
    [datepickerView addSubview:line1];
    
    UIButton *btn=[[UIButton alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT/2-50, SCREEN_WIDTH-40*W, 50)];
    btn.titleLabel.textAlignment=NSTextAlignmentCenter;
    [btn setTitleColor:[UIColor colorWithRed:(CGFloat)21/255 green:(CGFloat)124/255 blue:(CGFloat)244/255 alpha:1.0] forState:UIControlStateNormal];
    [btn setTitle:@"完成" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(tapped_gettotime) forControlEvents:UIControlEventTouchUpInside];
    [datepickerView addSubview:btn];

}

- (void)tapped_selectFromTime{
    self.tabBarController.tabBar.userInteractionEnabled=NO;
    //点击选择开始时间
    back=YES;
    backView=[[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    backView.backgroundColor=[UIColor colorWithWhite:0.2 alpha:0.5];
    [self.view addSubview:backView];
    
    btn_enlarge.enabled=NO;
    btn_reduce.enabled=NO;
    btn_remarktype.enabled=NO;
    btn_maptype.enabled=NO;
    datepickerView=[[UIView alloc]initWithFrame:CGRectMake(20*W, SCREEN_HEIGHT/4, SCREEN_WIDTH-40*W, SCREEN_HEIGHT/2)];
    datepickerView.backgroundColor=[UIColor whiteColor];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *str_date=btn_date.titleLabel.text;
    str_date=[str_date stringByAppendingString:@" "];
    str_date=[[str_date stringByAppendingString:btn_fromtime.titleLabel.text]stringByAppendingString:@":00"];
    NSDate *date = [dateFormatter dateFromString:str_date];
    
    [backView addSubview:datepickerView];
    timepicker=[[UIDatePicker alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH-40*W, SCREEN_HEIGHT/2)];
    timepicker.date=date;
    timepicker.datePickerMode=UIDatePickerModeTime;
    // datepicker.backgroundColor=[UIColor blackColor];
    timepicker.frame=CGRectMake(0, 0, SCREEN_WIDTH-40*W, SCREEN_HEIGHT/2-50);
    [datepickerView addSubview:timepicker];
    UIView *line1=[[UIView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT/2-50, SCREEN_WIDTH-40*W, 1)];
    line1.backgroundColor=[UIColor colorWithRed:(CGFloat)21/255 green:(CGFloat)124/255 blue:(CGFloat)244/255 alpha:1.0];
    [datepickerView addSubview:line1];
    
    UIButton *btn=[[UIButton alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT/2-50, SCREEN_WIDTH-40*W, 50)];
    btn.titleLabel.textAlignment=NSTextAlignmentCenter;
    [btn setTitleColor:[UIColor colorWithRed:(CGFloat)21/255 green:(CGFloat)124/255 blue:(CGFloat)244/255 alpha:1.0] forState:UIControlStateNormal];
    [btn setTitle:@"完成" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(tapped_getfrometime) forControlEvents:UIControlEventTouchUpInside];
    [datepickerView addSubview:btn];
}

- (void)tapped_gettotime{
    //点击完成终止时间
    self.tabBarController.tabBar.userInteractionEnabled=YES;
    NSDate *date=timepicker.date;
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"HH:mm"];
    NSString *totime=[dateFormatter stringFromDate:date];
    NSString *frometime=btn_fromtime.titleLabel.text;
    NSComparisonResult result=[totime compare:frometime];
    if(result ==-1){
        [PopMsg showMessage:@"结束时间不能小于开始时间" Lasttime:1.0f];
    }
    else{
        [btn_totime setTitle:totime forState:UIControlStateNormal];
        [self dorequestForgetHistoryPositions];
    }
    
    [backView removeFromSuperview];
    
    btn_enlarge.enabled=YES;
    btn_reduce.enabled=YES;
    btn_remarktype.enabled=YES;
    btn_maptype.enabled=YES;
    back=NO;

}

- (void)tapped_getfrometime{
    self.tabBarController.tabBar.userInteractionEnabled=YES;
    //点击完成开始时间
    NSDate *date=timepicker.date;
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"HH:mm"];
    NSString *totime=btn_totime.titleLabel.text;
    NSString *frometime=[dateFormatter stringFromDate:date];
    NSComparisonResult result=[frometime compare:totime];
    if(result==1){
        [PopMsg showMessage:@"开始时间不能大于结束时间" Lasttime:1.0f];
    }
    else{
        [btn_fromtime setTitle:[dateFormatter stringFromDate:date] forState:UIControlStateNormal];
        [self dorequestForgetHistoryPositions];

    }
    [backView removeFromSuperview];
    
    btn_enlarge.enabled=YES;
    btn_reduce.enabled=YES;
    btn_remarktype.enabled=YES;
    btn_maptype.enabled=YES;
    back=NO;

}

- (void)tapped_selectDate{
    self.tabBarController.tabBar.userInteractionEnabled=NO;
    //点击选中日期
    back=YES;
    backView=[[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    backView.backgroundColor=[UIColor colorWithWhite:0.2 alpha:0.5];
    [self.view addSubview:backView];
    
    btn_enlarge.enabled=NO;
    btn_reduce.enabled=NO;
    btn_remarktype.enabled=NO;
    btn_maptype.enabled=NO;
    datepickerView=[[UIView alloc]initWithFrame:CGRectMake(20*W, SCREEN_HEIGHT/4, SCREEN_WIDTH-40*W, SCREEN_HEIGHT/2)];
    datepickerView.backgroundColor=[UIColor whiteColor];
    
    [backView addSubview:datepickerView];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *str_date=btn_date.titleLabel.text;
    str_date=[str_date stringByAppendingString:@" 00:00:00"];
    NSDate *date = [dateFormatter dateFromString:str_date];

    datepicker=[[UIDatePicker alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH-40*W, SCREEN_HEIGHT/2)];
    datepicker.date=date;
    datepicker.datePickerMode=UIDatePickerModeDate;
   // datepicker.backgroundColor=[UIColor blackColor];
    datepicker.frame=CGRectMake(0, 0, SCREEN_WIDTH-40*W, SCREEN_HEIGHT/2-50);
    [datepickerView addSubview:datepicker];
    UIView *line1=[[UIView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT/2-50, SCREEN_WIDTH-40*W, 1)];
    line1.backgroundColor=[UIColor colorWithRed:(CGFloat)21/255 green:(CGFloat)124/255 blue:(CGFloat)244/255 alpha:1.0];
    [datepickerView addSubview:line1];
    
    UIButton *btn=[[UIButton alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT/2-50, SCREEN_WIDTH-40*W, 50)];
    btn.titleLabel.textAlignment=NSTextAlignmentCenter;
    [btn setTitleColor:[UIColor colorWithRed:(CGFloat)21/255 green:(CGFloat)124/255 blue:(CGFloat)244/255 alpha:1.0] forState:UIControlStateNormal];
    [btn setTitle:@"完成" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(tapped_getdate) forControlEvents:UIControlEventTouchUpInside];
    [datepickerView addSubview:btn];

}

- (void)tapped_getdate{
    
    self.tabBarController.tabBar.userInteractionEnabled=YES;
    //点击完成日期确认
    NSDate *date=datepicker.date;
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    [btn_date setTitle:[dateFormatter stringFromDate:date] forState:UIControlStateNormal];
    [backView removeFromSuperview];
    [self dorequestForgetHistoryPositions];

    btn_enlarge.enabled=YES;
    btn_reduce.enabled=YES;
    btn_remarktype.enabled=YES;
    btn_maptype.enabled=YES;
    back=NO;
}

- (void)tapped_reducedate{
    //点击返回前一天
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *str_date=btn_date.titleLabel.text;
    str_date=[str_date stringByAppendingString:@" 00:00:00"];
    NSDate *date = [dateFormatter dateFromString:str_date];
    NSLog(@"%@", date);
    NSDate *leftdate=[NSDate dateWithTimeInterval:-24*60*60 sinceDate:date];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *left=[dateFormatter stringFromDate:leftdate];
    [btn_date setTitle:left forState:UIControlStateNormal];
    [self dorequestForgetHistoryPositions];
}

- (void)tapped_recreasedate{
    //点击达到后一天
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *str_date=btn_date.titleLabel.text;
    str_date=[str_date stringByAppendingString:@" 00:00:00"];
    NSDate *date = [dateFormatter dateFromString:str_date];
    NSLog(@"%@", date);
    NSDate *rightdate=[NSDate dateWithTimeInterval:24*60*60 sinceDate:date];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *right=[dateFormatter stringFromDate:rightdate];
    [btn_date setTitle:right forState:UIControlStateNormal];
    [self dorequestForgetHistoryPositions];
}


#pragma mark - 网络请求

- (void)dorequestForGetCurrentLoction2{
    NSDictionary *pardic = nil;
    if ([self.userOrTourist isEqualToString:@"1"]) {
        pardic = @{@"bid":[[NSUserDefaults standardUserDefaults]objectForKey:@"bid"]};
    }
    NSString *newurl=[urlstring stringByAppendingString:@"getRTPosition.do"];
    [K_AppDelegate GenerateHTTPRequestWithUrl:newurl withParam:pardic success:^(AFHTTPRequestOperation *op,id responseObject){
        NSDictionary *responseDic=(NSDictionary *)responseObject;
        CLLocationCoordinate2D coordinate;
        CGFloat locaLatitude=[[responseDic objectForKey:@"lat"]floatValue];
        CGFloat locaLongitude=[[responseDic objectForKey:@"lon"]floatValue];
        coordinate=(CLLocationCoordinate2D){locaLatitude,locaLongitude};
        

//       地图的中心点坐标操作
        mapView.centerCoordinate=coordinate;
//       指针的中心点坐标操作
        anni.coordinate=coordinate;
        
        option.reverseGeoPoint=coordinate;
        
        //反地址编码
        BOOL flag=[search reverseGeoCode:option];
        
        NSString *labtime=@"定位时间: ";
        
        NSNumber *time=[responseDic objectForKey:@"posdate"];
        
        NSDate * date = [NSDate dateWithTimeIntervalSince1970:time.doubleValue/1000];
        
        NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
        NSString *strtime=[formatter stringFromDate:date];
        paopaoLab_time.text=[labtime stringByAppendingString:strtime];
        
        NSString *lab_phone=@"告警号码: ";
        NSString *phonenumber=[[NSUserDefaults standardUserDefaults]objectForKey:@"phonenumber"];
        if(phonenumber!=nil){
            paopaoLab_phone.text=[lab_phone stringByAppendingString:phonenumber];
        }
        
    }failure:^(AFHTTPRequestOperation *op,NSError *error){
        [PopMsg showMessage:@"网络错误" Lasttime:1.0f];
        
    }];
    
}



//时时定位但是不居于中心位置
- (void)dorequestForGetCurrentLoction3{
    NSDictionary *pardic = nil;
    if ([self.userOrTourist isEqualToString:@"1"]) {
        pardic = @{@"bid":[[NSUserDefaults standardUserDefaults]objectForKey:@"bid"]};
    }
    NSString *newurl=[urlstring stringByAppendingString:@"getRTPosition.do"];
    [K_AppDelegate GenerateHTTPRequestWithUrl:newurl withParam:pardic success:^(AFHTTPRequestOperation *op,id responseObject){
        NSDictionary *responseDic=(NSDictionary *)responseObject;
        CLLocationCoordinate2D coordinate;
        CGFloat locaLatitude=[[responseDic objectForKey:@"lat"]floatValue];
        CGFloat locaLongitude=[[responseDic objectForKey:@"lon"]floatValue];
        coordinate=(CLLocationCoordinate2D){locaLatitude,locaLongitude};
        
//        mapView.centerCoordinate=coordinate;
        anni.coordinate=coordinate;
        
        option.reverseGeoPoint=coordinate;
        
        //反地址编码
        BOOL flag=[search reverseGeoCode:option];
        
        NSString *labtime=@"定位时间: ";
        
        NSNumber *time=[responseDic objectForKey:@"posdate"];
        
        NSDate * date = [NSDate dateWithTimeIntervalSince1970:time.doubleValue/1000];
        
        NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
        NSString *strtime=[formatter stringFromDate:date];
        paopaoLab_time.text=[labtime stringByAppendingString:strtime];
        
        NSString *lab_phone=@"告警号码: ";
        NSString *phonenumber=[[NSUserDefaults standardUserDefaults]objectForKey:@"phonenumber"];
        if(phonenumber!=nil){
            paopaoLab_phone.text=[lab_phone stringByAppendingString:phonenumber];
        }
        
    }failure:^(AFHTTPRequestOperation *op,NSError *error){
        [PopMsg showMessage:@"网络错误" Lasttime:1.0f];
        
    }];
    
}




//获得服务器的多个海拔经纬度
- (void)dorequestForgetHistoryPositions{
    

    NSArray* array = [NSArray arrayWithArray:mapView.annotations];
    
   
    
    [mapView removeAnnotations:array];
    
    array = [NSArray arrayWithArray:mapView.overlays];
 
    [mapView removeOverlays:array];

    count_start=0;
    count_end=1;
    array_historyPositions=[NSMutableArray new];
    //获取历史轨迹网络请求
    start=YES;
    end=YES;
    self.centerbtn.enabled=NO;
    [loadmsg loadImages];
    btn_totime.enabled=NO;
    btn_fromtime.enabled=NO;
    leftdate.enabled=NO;
    rightdate.enabled=NO;
    btn_date.enabled=NO;

//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        sleep(startloadtime);
//        dispatch_async(dispatch_get_main_queue(), ^{
//            if(start==YES){
//                [loadmsg loadImages];
//            }
//        });
//    });
//    
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        sleep(startloadtime+endloadtime);
//        dispatch_async(dispatch_get_main_queue(), ^{
//            end=NO;
//            if(start==NO){
//                [loadmsg.imageview removeFromSuperview];
//            }
//        });
//    });
    NSString *date=btn_date.titleLabel.text;
    NSString *frometime=btn_fromtime.titleLabel.text;
    NSString *totime=btn_totime.titleLabel.text;
    NSString *startTime=[[[date stringByAppendingString:@" "]stringByAppendingString:frometime]stringByAppendingString:@":00"];
    NSString *endTime=[[[date stringByAppendingString:@" "]stringByAppendingString:totime]stringByAppendingString:@":00"];

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;

    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *fromedate=[formatter dateFromString:startTime];
    NSDate *todate=[formatter dateFromString:endTime];
    
    //long a=fromedate.timeIntervalSince1970;
    NSString *timeIntervalFrom=[NSString stringWithFormat:@"%lld",(long long)[fromedate timeIntervalSince1970]*1000];
    NSString *timeIntervalTo=[NSString stringWithFormat:@"%lld",(long long)[todate timeIntervalSince1970]*1000];
    
    NSDictionary *pardic=@{@"bid":[[NSUserDefaults standardUserDefaults]objectForKey:@"bid"],@"startTime":timeIntervalFrom,@"endTime":timeIntervalTo};
    NSString *newurl=[urlstring stringByAppendingString:@"getHistoryPositions.do"];
    [K_AppDelegate GenerateHTTPRequestWithUrl:newurl withParam:pardic success:^(AFHTTPRequestOperation *op,id responseObject){
        start=NO;
        self.centerbtn.enabled=YES;
//        if(end==NO){
//            [loadmsg.imageview removeFromSuperview];
//        }
        
        
        NSDictionary *responseDic=(NSDictionary *)responseObject;
        
        
        NSString *msg = [responseDic objectForKey:@"msg"];
        if (msg) {
            NSString *message=[msg stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            [PopMsg showMessage:message Lasttime:1.0f];
        }
        
        
        
        long flag=[[responseDic objectForKey:@"flag"]integerValue];
        if(flag==0){
            NSArray *positions=[responseDic objectForKey:@"positions"];
            for(NSDictionary *dic in positions){
                
                NSString *lat=[dic objectForKey:@"lat"];
                NSString *lon=[dic objectForKey:@"lon"];
                
                
            
                if(array_historyPositions.count==0){
                    [array_historyPositions addObject:dic];
                }
                else{
                    for(long i=array_historyPositions.count-1;i>=0;i--){
                        NSDictionary *dic1=array_historyPositions[i];
                        NSString *lat1=[dic1 objectForKey:@"lat"];
                        NSString *lon1=[dic1 objectForKey:@"lon"];
                        if([lat isEqualToString:lat1]&&[lon isEqualToString:lon1]){
                            break;
                        }
                        if(i==0){
                            [array_historyPositions addObject:dic];
                        }
                        
                    }
                }
                
            }
    
//              NSLog(@"11a  %ld  %@   ",array_historyPositions.count,array_historyPositions);
            //进行降序排列和采集时间进行比较进行重新组合新的数组
            array_historyPositions=[array_historyPositions sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *dic1,NSDictionary *dic2){
                NSComparisonResult result=[[dic1 objectForKey:@"postdate"]compare:[dic2 objectForKey:@"postdate"]];
                return result;
            }];
            
//            获得历史定点轨迹的海拔经纬度
//            NSLog(@"22a  %ld  %@   ",array_historyPositions.count,array_historyPositions);
            
            if(tag_remark==0){
             
                if(array_historyPositions.count>=2){
//                    历史轨迹绘制操作
                    [self donextforRemark];//坐标数大于等于2
                }
                else if(array_historyPositions.count==1){
//                    坐标为1个的时候进行另外操作
                    [self donextforRemarkonlyOnepoint];//坐标数为1
                }
                else{
                    //无坐标
                    [loadmsg.imageview removeFromSuperview];
                    btn_totime.enabled=YES;
                    btn_fromtime.enabled=YES;
                    leftdate.enabled=YES;
                    rightdate.enabled=YES;
                    btn_date.enabled=YES;
                }
            }
            
//            请求网路的时候也一块请求锚点定位的坐标
            else{
                //锚点定位
                [loadmsg.imageview removeFromSuperview];
                btn_totime.enabled=YES;
                btn_fromtime.enabled=YES;
                leftdate.enabled=YES;
                rightdate.enabled=YES;
                btn_date.enabled=YES;
                [self donextformaodianRemark];
            }
        }
        else{
            //flag不为0
            [loadmsg.imageview removeFromSuperview];
            btn_totime.enabled=YES;
            btn_fromtime.enabled=YES;
            leftdate.enabled=YES;
            rightdate.enabled=YES;
            btn_date.enabled=YES;

        }
        
    }failure:^(AFHTTPRequestOperation *op,NSError *error){
        start=NO;
        self.centerbtn.enabled=YES;
        [loadmsg.imageview removeFromSuperview];

//        if(end==NO){
//            [loadmsg.imageview removeFromSuperview];
//        }
        btn_totime.enabled=YES;
        btn_fromtime.enabled=YES;
        leftdate.enabled=YES;
        rightdate.enabled=YES;
        btn_date.enabled=YES;
        [PopMsg showMessage:@"网络错误" Lasttime:1.0f];
     }];
}


//从网络获取经纬度显示当前车辆的状态位置，来进行反向地理编码
- (void)dorequestForGetCurrentLoction{
    //获取实时位置接口
    start=YES;
    end=YES;
    self.rightbtn.enabled=NO;
    //self.tabBarController.editing=NO;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        sleep(startloadtime);
        dispatch_async(dispatch_get_main_queue(), ^{
            if(start==YES){
                [loadmsg loadImages];
            }
        });
    });
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        sleep(startloadtime+endloadtime);
        dispatch_async(dispatch_get_main_queue(), ^{
            end=NO;
            if(start==NO){
                [loadmsg.imageview removeFromSuperview];
            }
        });
    });
    NSDictionary *pardic = nil;
    
    
    NSLog(@"dasdnasdasdas  %@",[[NSUserDefaults standardUserDefaults]objectForKey:@"bid"]);
    
    
    
    
    if ([self.userOrTourist isEqualToString:@"1"]) {
       pardic = @{@"bid":[[NSUserDefaults standardUserDefaults]objectForKey:@"bid"]};
    }
    NSString *newurl=[urlstring stringByAppendingString:@"getRTPosition.do"];
    [K_AppDelegate GenerateHTTPRequestWithUrl:newurl withParam:pardic success:^(AFHTTPRequestOperation *op,id responseObject){
        NSArray *array=mapView.annotations;
        if(array.count==0){
            [mapView addAnnotation:anni];
        }
        
        
        
        //NSLog(@"duaduuau  %@",responseObject);
        
        start=NO;
        self.rightbtn.enabled=YES;
        if(end==NO){
            [loadmsg.imageview removeFromSuperview];
        }
        NSDictionary *responseDic=(NSDictionary *)responseObject;
        CLLocationCoordinate2D coordinate;
    
        CGFloat locaLatitude=[[responseDic objectForKey:@"lat"]floatValue];
        CGFloat locaLongitude=[[responseDic objectForKey:@"lon"]floatValue];
        coordinate=(CLLocationCoordinate2D){locaLatitude,locaLongitude};

        mapView.centerCoordinate=coordinate;
        anni.coordinate=coordinate;
        
        option.reverseGeoPoint=coordinate;
        
        
        

        
        
        
        //反地址编码
        BOOL flag=[search reverseGeoCode:option];
        
        NSString *labtime=@"定位时间: ";
       
        NSNumber *time=[responseDic objectForKey:@"posdate"];
        
        NSDate * date = [NSDate dateWithTimeIntervalSince1970:time.doubleValue/1000];
        
        NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSString *strtime=[formatter stringFromDate:date];
        paopaoLab_time.text=[labtime stringByAppendingString:strtime];
        
        NSString *lab_phone=@"告警号码: ";
        NSString *phonenumber=[[NSUserDefaults standardUserDefaults]objectForKey:@"phonenumber"];
        if(phonenumber!=nil){
            paopaoLab_phone.text=[lab_phone stringByAppendingString:phonenumber];
        }
        
    }failure:^(AFHTTPRequestOperation *op,NSError *error){
        start=NO;
        self.rightbtn.enabled=YES;
        if(end==NO){
            [loadmsg.imageview removeFromSuperview];
        }
        [PopMsg showMessage:@"网络错误" Lasttime:1.0f];

    }];

}
#pragma mark获取历史轨迹
- (void)dorequestForGetbicycleState{
    //获取车辆当前状态
    start2=YES;
    end2=YES;
    
    //loadmsg=[PopLoadMsg new];
    self.tabBarController.editing=NO;
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        sleep(startloadtime);
//        dispatch_async(dispatch_get_main_queue(), ^{
//            if(start2==YES){
//                [loadmsg loadImages];
//            }
//        });
//    });
//    
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        sleep(startloadtime+endloadtime);
//        dispatch_async(dispatch_get_main_queue(), ^{
//            end2=NO;
//            if(start2==NO){
//                [loadmsg.imageview removeFromSuperview];
//            }
//        });
//    });
//loginid 登陆手机号
    NSString *loginid=[[NSUserDefaults standardUserDefaults]objectForKey:@"phonenumber"];
    if(loginid==nil){
        loginid=@"";
    }
    NSDictionary *pardic=@{@"loginId":loginid};
    NSString *newurl=[urlstring stringByAppendingString:@"getEbicycleInfo.do"];
//    [K_AppDelegate GenerateHTTPRequestWithUrl:newurl withParam:pardic success:^(AFHTTPRequestOperation *op,id responseObject){
//        start2=NO;
//        if(end2==NO)
//        {
//            [loadmsg.imageview removeFromSuperview];
//        }
//        NSDictionary *responseDic=(NSDictionary *)responseObject;
//        NSString *msg = [responseDic objectForKey:@"msg"];
//        if (msg) {
//            NSString *message=[msg stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//            [PopMsg showMessage:message Lasttime:1.0f];
//        }
//    
//        brand 为品牌 bid 车辆id plateNumber 车牌号  frameID 车架号  simId sim号 color 颜色 brandType 型号
//        pictureUrl 图片地址   status 车辆状态   0-正常  1-被盗
//        
//        int flag=[[responseDic objectForKey:@"flag"]integerValue];
//        NSLog(@"12312322  %@",responseObject);
//        
//        if(flag==0){
//            NSArray *bicycleArray=[responseDic objectForKey:@"bicycleLists"];
//            NSDictionary *dic=bicycleArray[0];
//            
//            long status=[[dic objectForKey:@"status"]longValue];
//            if(status==0){
//                UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"历史轨迹按钮未激活" message:@"历史轨迹按钮仅在丢车报警后激活" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
//                [alert show];
//                
//            }
        
//            当报警之后进行历史轨迹搜索进行操作
//            else{
        
                
                index=2;
                btn_remarktype.hidden=NO;
                timebackview.hidden=NO;
                datebackview.hidden=NO;
                line.hidden=NO;
                [self.centerbtn setImage:[UIImage imageNamed:@"top_icon01_on"] forState:UIControlStateNormal];
                [self.rightbtn setImage:[UIImage imageNamed:@"top_icon02_on"] forState:UIControlStateNormal];
                [timer invalidate];
//                移除当前定位的点坐标
                [mapView removeAnnotation:anni];
                [self dorequestForgetHistoryPositions];
//            }
//        }
//        
//    }failure:^(AFHTTPRequestOperation *op,NSError *error){
//        start2=NO;
//        if(end2==NO){
//            [loadmsg.imageview removeFromSuperview];
//        }
//        [PopMsg showMessage:@"网络错误" Lasttime:1.0f];
//        
//    }];
    
}

// 通过链接网络获取告警状态
- (void)getAlarmStatus {

    NSString * loginId = [[NSUserDefaults standardUserDefaults]objectForKey:@"phonenumber"];
    NSString * bid     = [[NSUserDefaults standardUserDefaults]objectForKey:@"bid"];
    
    NSString * urlMethod = [NSString stringWithFormat:@"%@getAlarmStatus.do",urlstring];
    NSDictionary * paramDict = @{@"loginId":loginId,@"bid":bid};
    
    PopLoadMsg *loadView=[PopLoadMsg new];
    [loadView delayLoadImages];
    
    __weak __typeof(self)wself = self;
    [K_AppDelegate GenerateHTTPRequestWithUrl:urlMethod withParam: paramDict success:
     ^(AFHTTPRequestOperation *operation, id responseObject) {
         [loadView delayImagesRemove];
         NSDictionary * responseDict = responseObject;
         NSNumber * flag = nil;
         NSString *abnormalStatus = nil;
         NSString *lowPowerStatus = nil;
         NSString *cutStatus = nil;
         NSString *elecFenceStatus = nil;
         
         flag  = [responseDict objectForKey:@"flag"];
         if (!flag)
         {
             NSLog(@"查询状态失败！");
             [PopMsg showMessage:@"查询状态失败！" Lasttime:2];
         }
         
         if ( 0 == flag.longValue )
         {
             abnormalStatus = [responseDict objectForKey:@"abnormalStatus"];
             lowPowerStatus = [responseDict objectForKey:@"lowPowerStatus"];
             cutStatus = [responseDict objectForKey:@"cutStatus"];
             elecFenceStatus = [responseDict objectForKey:@"elecFenceStatus"];
             if ([abnormalStatus isEqualToString:@"0"] &&
                 [lowPowerStatus isEqualToString:@"0"] &&
                 [cutStatus isEqualToString:@"0"] &&
                 [elecFenceStatus isEqualToString:@"0"]) {
                 wself.annotationView.image = [UIImage imageNamed:@"3pic_icon01.png"];   //把大头针换成别的图片
                 paopaoLab_status.text = [paopaoLab_status.text stringByAppendingString:@"正常"];
             }
             else {
                 wself.annotationView.image = [UIImage imageNamed:@"3pic_icon01_abnormal"];
                 paopaoLab_status.text = @"当前状态:";
                 if ([abnormalStatus isEqualToString:@"1"]) {
                     paopaoLab_status.text = [paopaoLab_status.text stringByAppendingString:@"非法位移"];
                 }else if ([abnormalStatus isEqualToString:@"2"]) {
                     paopaoLab_status.text = [paopaoLab_status.text stringByAppendingString:@"震动"];
                 }else if ([abnormalStatus isEqualToString:@"3"]) {
                     paopaoLab_status.text = [paopaoLab_status.text stringByAppendingString:@"锁定"];
                 }
                 
                 if ([lowPowerStatus isKindOfClass:@"1"]) {
                     paopaoLab_status.text = paopaoLab_status.text = [paopaoLab_status.text stringByAppendingString:@"电量即将耗尽，请及时充电"];
                 }else if ([lowPowerStatus isEqualToString:@"2"]) {
                     paopaoLab_status.text = [paopaoLab_status.text stringByAppendingString:@"当前状态:电量已耗尽，请及时充电"];
                 }
                 
                 if ([cutStatus isEqualToString:@"1"]) {
                     paopaoLab_status.text = [paopaoLab_status.text stringByAppendingString:@"当前状态:您的设备已被剪断"];
                 }
                 
                 if ([elecFenceStatus isEqualToString:@"1"]) {
                     paopaoLab_status.text = [paopaoLab_status.text stringByAppendingString:@"当前状态:您的设备已超出围栏"];
                 }
             }
        }
         else
         {
             NSLog(@"获取状态失败！");
             [PopMsg showMessage:@"获取状态失败" Lasttime:2];
         }
         
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         [loadmsg delayImagesRemove];
         [PopMsg showMessage:@"网络连接失败" Lasttime:2];
         
     }];

}

#pragma mark - 地图配置当个数为1的时候进行操作


- (void)donextforRemarkonlyOnepoint{
    NSDictionary *dic_start=array_historyPositions[0];
    NSString *lat=[dic_start objectForKey:@"lat"];
    NSString *lon=[dic_start objectForKey:@"lon"];
    CLLocationCoordinate2D startcoor;
    startcoor.latitude=[lat doubleValue];
    startcoor.longitude=[lon doubleValue];
    
    NSDictionary *dic_end=array_historyPositions[0];
    lat=[dic_end objectForKey:@"lat"];
    lon=[dic_end objectForKey:@"lon"];
    CLLocationCoordinate2D endcoor;
    endcoor.latitude=[lat doubleValue];
    endcoor.longitude=[lon doubleValue];
  
    [self remark_guiji_startnode:startcoor andendnode:endcoor];

}

- (UIImage *)usePostDateToGetImage:(double)timeInterval{
    //获取展示时间的图片
    UIView *returnview=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 440, 50)];
    UIImageView *imageview2=[[UIImageView alloc]initWithFrame:CGRectMake(200, 0, 40, 50)];
    imageview2.image=[UIImage imageNamed:@"anchor_icon.png"];
    
//    UIImageView *imageview=[[UIImageView alloc]initWithFrame:CGRectMake(240, 0, 200, 50)];
//    imageview.image=[UIImage imageNamed:@"5pic_location05"];
//    NSDate *date=[NSDate dateWithTimeIntervalSince1970:timeInterval/1000];
//    NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
//    [formatter setDateFormat:@"yyyy-MM-dd HH:mm"];
//    NSString *text=[formatter stringFromDate:date];
//    UILabel *lab=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 200, 50)];
//    lab.font=[UIFont systemFontOfSize:19];
//    lab.textColor=[UIColor whiteColor];
//    lab.textAlignment=NSTextAlignmentCenter;
//    lab.text=text;
//    [imageview addSubview:lab];
    [returnview addSubview:imageview2];
//    [returnview addSubview:imageview];
    return [UIImage convertViewToImage:returnview];
}



#pragma mark 进行锚点描述操作进行自定义大头针
- (void)donextformaodianRemark{
    count=0;
    for(NSDictionary *dic in array_historyPositions){
        NSString *lat=[dic objectForKey:@"lat"];
        NSString *lon=[dic objectForKey:@"lon"];
        CLLocationCoordinate2D startcoor;
        startcoor.latitude=[lat doubleValue];
        startcoor.longitude=[lon doubleValue];
        BMKPointAnnotation *pointannotation=[[BMKPointAnnotation alloc]init];
        pointannotation.coordinate=startcoor;

        [mapView addAnnotation:pointannotation];
        count++;
        mapView.centerCoordinate=startcoor;
        BMKCoordinateRegion region ;//表示范围的结构体
        region.center=mapView.centerCoordinate;
        region.span.latitudeDelta=0.01;
        region.span.longitudeDelta=0.01;
        mapView.region=region;

    }
    

}

- (void)donextforRemark{
    
    NSDictionary *dic_start= array_historyPositions[count_start];
    

    
    NSString *lat=[dic_start objectForKey:@"lat"];
    NSString *lon=[dic_start objectForKey:@"lon"];
    CLLocationCoordinate2D startcoor;
    startcoor.latitude=[lat doubleValue];
    startcoor.longitude=[lon doubleValue];
    
    
    NSDictionary *dic_end=array_historyPositions[count_end];
    lat=[dic_end objectForKey:@"lat"];
    lon=[dic_end objectForKey:@"lon"];
    CLLocationCoordinate2D endcoor;
    endcoor.latitude=[lat doubleValue];
    endcoor.longitude=[lon doubleValue];
    count_start++;
    count_end++;
    
    
    NSLog(@"最新时时数据记录    %d    %d",count_start,count_end);
    
    [self remark_guiji_startnode:startcoor andendnode:endcoor];
}
#pragma mark 通过网络请求返回的节点进行绘制线条
- (void)remark_guiji_startnode:(CLLocationCoordinate2D )startcoordinate andendnode:(CLLocationCoordinate2D )endcoordinate{
    BMKPlanNode *startnode=[[BMKPlanNode alloc]init];
    startnode.pt=startcoordinate;
//    startnode.name=@"天安门";
//    startnode.cityName=@"北京市";
    BMKPlanNode *endnode=[[BMKPlanNode alloc]init];
   
    endnode.pt=endcoordinate;
//    endnode.cityName=@"北京市";
//    endnode.name=@"百度大厦";
    BMKWalkingRoutePlanOption *walking=[[BMKWalkingRoutePlanOption alloc]init];
    walking.from=startnode;
    walking.to=endnode;
    BOOL flag= [routeSearch walkingSearch:walking];
    if(flag)
    {
        NSLog(@"walking检索发送成功");
    }
    else
    {
        NSLog(@"walking检索发送失败");
    }
}


#pragma mark根据获得的节点进行绘制轨迹路线图

- (void)onGetWalkingRouteResult:(BMKRouteSearch*)searcher result:(BMKWalkingRouteResult*)result errorCode:(BMKSearchErrorCode)error{
    
//    NSArray* array = [NSArray arrayWithArray:mapview.annotations];
//    [mapview removeAnnotations:array];
//    array = [NSArray arrayWithArray:mapview.overlays];
//    [mapview removeOverlays:array];
    if (error == BMK_SEARCH_NO_ERROR) {
        //在此处理正常结果
        
        NSLog(@"111");
        BMKWalkingRouteLine* plan = (BMKWalkingRouteLine*)[result.routes objectAtIndex:0];
        int size = [plan.steps count];
        int planPointCounts = 0;
//        if(size==1){
//            if(count_start==1){
//                
//            }
//            else{
//                count_start--;
//            }
//
//            if(count_end<array_historyPositions.count){
//                [self donextforRemark];
//            }
//
//            return;
//        }
        
        for (int i = 0; i < size; i++) {
            BMKWalkingStep* transitStep = [plan.steps objectAtIndex:i];
            if(i==0){
                if(count_start==1){
                    RouteAnnotation* item = [[RouteAnnotation alloc]init];
                    item.coordinate = plan.starting.location;
                    item.title = @"起点";
                    item.type = 0;
                    [mapView addAnnotation:item]; // 添加起点标注
                }
                else if(count_start==array_historyPositions.count-1){
                    RouteAnnotation* item = [[RouteAnnotation alloc]init];
                    item.coordinate = plan.terminal.location;
                    item.title = @"终点";
                    item.type = 1;
                    [mapView addAnnotation:item]; // 添加终点标注
                }

                
            }
            else if(i==size-1){
                if(count_start==array_historyPositions.count-1){
                    RouteAnnotation* item = [[RouteAnnotation alloc]init];
                    item.coordinate = plan.terminal.location;
                    item.title = @"终点";
                    item.type = 1;
                    [mapView addAnnotation:item]; // 添加终点标注
                }
            }
            //count_start=count_end-1;
            //添加annotation节点
            RouteAnnotation* item = [[RouteAnnotation alloc]init];
            item.coordinate = transitStep.entrace.location;
            item.title = transitStep.entraceInstruction;
            item.degree = transitStep.direction * 30;
            item.type = 4;
            [mapView addAnnotation:item];
            
            //轨迹点总数累计
            planPointCounts += transitStep.pointsCount;
        }
        
        //轨迹点
        BMKMapPoint * temppoints = new BMKMapPoint[planPointCounts];
        int i = 0;
        for (int j = 0; j < size; j++) {
            BMKWalkingStep* transitStep = [plan.steps objectAtIndex:j];
            int k=0;
            for(k=0;k<transitStep.pointsCount;k++) {
                temppoints[i].x = transitStep.points[k].x;
                temppoints[i].y = transitStep.points[k].y;
                i++;
            }
        }
        // 通过points构建BMKPolyline
//        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//            polyLine = [BMKPolyline polylineWithPoints:temppoints count:planPointCounts];
//            [mapview addOverlay:polyLine];
//            delete []temppoints;
//
//            dispatch_async(dispatch_get_main_queue(), ^{
//                
//                if(count_end==array_historyPositions.count){
//                    [self mapViewFitPolyLine:polyLine];
//                }
//            });
//        });
        BMKPolyline* polyLine = [BMKPolyline polylineWithPoints:temppoints count:planPointCounts];
        [mapView addOverlay:polyLine]; // 添加路线overlay
        delete []temppoints;
      //  NSDictionary *dic_end=array_historyPositions[count_end-1];
        NSDictionary *dic_start=array_historyPositions[count_end-1];
        NSString *lat=[dic_start objectForKey:@"lat"];
        NSString *lon=[dic_start objectForKey:@"lon"];
        CLLocationCoordinate2D startcoor;
        startcoor.latitude=[lat doubleValue];
        startcoor.longitude=[lon doubleValue];

        
        if(count_end==array_historyPositions.count){
           // [self mapViewFitPolyLine:polyLine];
            [self customFitMapView:startcoor];
            [loadmsg.imageview removeFromSuperview];
            btn_totime.enabled=YES;
            btn_fromtime.enabled=YES;
            leftdate.enabled=YES;
            rightdate.enabled=YES;
            btn_date.enabled=YES;
        }
    }
    else if (error == BMK_SEARCH_AMBIGUOUS_ROURE_ADDR){
        //当路线起终点有歧义时通，获取建议检索起终点
        //result.routeAddrResult
        NSLog(@"222");
        
    }
    else {
        
        //[PopMsg showMessage:@"抱歉，未找到结果" Lasttime:1.0f];
        NSLog(@"抱歉，未找到结果");
        // 添加折线覆盖物
//        if(count_start==1){
//            
//        }
//        else{
//            count_start--;
//        }
        NSDictionary *dic_start=array_historyPositions[count_start-1];
        NSString *lat=[dic_start objectForKey:@"lat"];
        NSString *lon=[dic_start objectForKey:@"lon"];
        CLLocationCoordinate2D startcoor;
        startcoor.latitude=[lat doubleValue];
        startcoor.longitude=[lon doubleValue];
        if(count_start==1){
            RouteAnnotation* item = [[RouteAnnotation alloc]init];
            item.coordinate = startcoor;
            item.title = @"起点";
            item.type = 0;
            [mapView addAnnotation:item]; // 添加起点标注
        }
        
        NSDictionary *dic_end=array_historyPositions[count_end-1];
        lat=[dic_end objectForKey:@"lat"];
        lon=[dic_end objectForKey:@"lon"];
        CLLocationCoordinate2D endcoor;
        endcoor.latitude=[lat doubleValue];
        endcoor.longitude=[lon doubleValue];
        if(count_start==array_historyPositions.count-1){
            RouteAnnotation* item = [[RouteAnnotation alloc]init];
            item.coordinate = endcoor;
            item.title = @"终点";
            item.type = 1;
            [mapView addAnnotation:item]; // 添加终点标注
        }

        CLLocationCoordinate2D coors[2] = {0};
        coors[0]=startcoor;
        
        coors[1]=endcoor;
        
        BMKPolyline* polyline = [BMKPolyline polylineWithCoordinates:coors count:2];
        [mapView addOverlay:polyline];
        if(count_end==array_historyPositions.count){
            //[self mapViewFitPolyLine:polyline];
            [self customFitMapView:endcoor];
            [loadmsg.imageview removeFromSuperview];
            btn_totime.enabled=YES;
            btn_fromtime.enabled=YES;
            leftdate.enabled=YES;
            rightdate.enabled=YES;
            btn_date.enabled=YES;

        }
    }
    if(count_end<array_historyPositions.count){
        [self donextforRemark];
    }
}

- (BMKOverlayView*)mapView:(BMKMapView *)map viewForOverlay:(id<BMKOverlay>)overlay
{
    if ([overlay isKindOfClass:[BMKPolyline class]]) {
        BMKPolylineView* polylineView = [[BMKPolylineView alloc] initWithOverlay:overlay];
        polylineView.fillColor = [[UIColor alloc] initWithRed:0 green:1 blue:1 alpha:1];
        polylineView.strokeColor = [[UIColor alloc] initWithRed:0 green:0 blue:1 alpha:0.7];
        polylineView.lineWidth = 3.0;
        
        return polylineView;
    }
    return nil;
}

- (void)customFitMapView:(CLLocationCoordinate2D)coor{
    
    //自定义适应地图尺寸和中心点
    BMKCoordinateRegion region ;//表示范围的结构体
    region.center=mapView.centerCoordinate;
    region.span.latitudeDelta=0.01;
    region.span.longitudeDelta=0.01;
    mapView.region=region;
    mapView.centerCoordinate=coor;

    
}

- (void)mapViewFitPolyLine:(BMKPolyline *) polyLine {
    //百度地图Demo地图划线适应百度地图尺寸和中心点
    
    CGFloat ltX, ltY, rbX, rbY;
    if (polyLine.pointCount < 1) {
        return;
    }
    BMKMapPoint pt = polyLine.points[0];
    ltX = pt.x, ltY = pt.y;
    rbX = pt.x, rbY = pt.y;
    for (int i = 1; i < polyLine.pointCount; i++) {
        BMKMapPoint pt = polyLine.points[i];
        if (pt.x < ltX) {
            ltX = pt.x;
        }
        if (pt.x > rbX) {
            rbX = pt.x;
        }
        if (pt.y > ltY) {
            ltY = pt.y;
        }
        if (pt.y < rbY) {
            rbY = pt.y;
        }
    }
    BMKMapRect rect;
    rect.origin = BMKMapPointMake(ltX , ltY);
    rect.size = BMKMapSizeMake(rbX - ltX, rbY - ltY);
    [mapView setVisibleMapRect:rect];
   // mapview.zoomLevel = mapview.zoomLevel - 0.3;
}


#pragma mark 反向地理编码对定位到当前位置进行大头针下落设置动画
//从网络获得经纬度进行反向地理编码然后设置大头针的自定义设置，反向地理编码设置当前位置
- (void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error{
    NSLog(@"地址是%@",result.address);
    NSString *address=result.address;
    NSString *lab_address=@"当前位置:";
//    反向地理编码获的地址进行展示
    paopaoLab_loc.text=[lab_address stringByAppendingString:address];
    CGSize size=CGSizeMake(200, 0);
    NSDictionary *fontdic=@{NSFontAttributeName:[UIFont systemFontOfSize:14]};
    CGFloat h=[self celheight:paopaoLab_loc.text andtextsize:size andfontdic:fontdic];
    paopaoLab_loc.frame=CGRectMake(10, 70, 200, h);

    paopao.frame=CGRectMake(-110, -(60+h + 20+6), 225, 60+h + 20+4);
}



//规划途径路径的线路图
- (BMKAnnotationView*)getRouteAnnotationView:(BMKMapView *)mapview viewForAnnotation:(RouteAnnotation*)routeAnnotation
{
    BMKAnnotationView* view = nil;
    switch (routeAnnotation.type) {
        case 0:
        {
            view = [mapview dequeueReusableAnnotationViewWithIdentifier:@"start_node"];
            if (view == nil) {
                view = [[BMKAnnotationView alloc]initWithAnnotation:routeAnnotation reuseIdentifier:@"start_node"];
                view.image = [UIImage imageNamed:@"6pic_start"];
                view.centerOffset = CGPointMake(0, -(view.frame.size.height * 0.5));
                view.canShowCallout = TRUE;
            }
            view.annotation = routeAnnotation;
        }
            break;
        case 1:
        {
            view = [mapview dequeueReusableAnnotationViewWithIdentifier:@"end_node"];
            if (view == nil) {
                view = [[BMKAnnotationView alloc]initWithAnnotation:routeAnnotation reuseIdentifier:@"end_node"];
                view.image = [UIImage imageNamed:@"6pic_end"];
                view.centerOffset = CGPointMake(0, -(view.frame.size.height * 0.5));
                view.canShowCallout = TRUE;
            }
            view.annotation = routeAnnotation;
        }
            break;
        case 2:
        {
            view = [mapview dequeueReusableAnnotationViewWithIdentifier:@"bus_node"];
            if (view == nil) {
                view = [[BMKAnnotationView alloc]initWithAnnotation:routeAnnotation reuseIdentifier:@"bus_node"];
                view.image = [UIImage imageWithContentsOfFile:[self getMyBundlePath1:@"images/icon_nav_bus.png"]];
                view.canShowCallout = TRUE;
            }
            view.annotation = routeAnnotation;
        }
            break;
        case 3:
        {
            view = [mapview dequeueReusableAnnotationViewWithIdentifier:@"rail_node"];
            if (view == nil) {
                view = [[BMKAnnotationView alloc]initWithAnnotation:routeAnnotation reuseIdentifier:@"rail_node"];
                view.image = [UIImage imageWithContentsOfFile:[self getMyBundlePath1:@"images/icon_nav_rail.png"]];
                view.canShowCallout = TRUE;
            }
            view.annotation = routeAnnotation;
        }
            break;
        case 4:
        {
            view = [mapview dequeueReusableAnnotationViewWithIdentifier:@"route_node"];
            if (view == nil) {
                view = [[BMKAnnotationView alloc]initWithAnnotation:routeAnnotation reuseIdentifier:@"route_node"];
                view.canShowCallout = TRUE;
            } else {
                [view setNeedsDisplay];
            }
            
            UIImage* image = [UIImage imageWithContentsOfFile:[self getMyBundlePath1:@"images/icon_direction.png"]];
            view.image = [image imageRotatedByDegrees:routeAnnotation.degree];
            view.annotation = routeAnnotation;
            
        }
            break;
        case 5:
        {
            view = [mapview dequeueReusableAnnotationViewWithIdentifier:@"waypoint_node"];
            if (view == nil) {
                view = [[BMKAnnotationView alloc]initWithAnnotation:routeAnnotation reuseIdentifier:@"waypoint_node"];
                view.canShowCallout = TRUE;
            } else {
                [view setNeedsDisplay];
            }
            
            UIImage* image = [UIImage imageWithContentsOfFile:[self getMyBundlePath1:@"images/icon_nav_waypoint.png"]];
            view.image = [image imageRotatedByDegrees:routeAnnotation.degree];
            view.annotation = routeAnnotation;
        }
            break;
        default:
            break;
    }
    
    return view;
}

- (NSString*)getMyBundlePath1:(NSString *)filename
{
    
    NSBundle * libBundle = MYBUNDLE ;
    if ( libBundle && filename ){
        NSString * s=[[libBundle resourcePath ] stringByAppendingPathComponent : filename];
        return s;
    }
    return nil ;
}

- (void)tapped_enlargemap
{
    [mapView zoomIn];
}

- (void)tapped_reducemap{
    [mapView zoomOut];
}


//自定义大头针操作
- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id <BMKAnnotation>)annotation{
    //自定义大头针图片
    if ([annotation isKindOfClass:[RouteAnnotation class]]) {
        return [self getRouteAnnotationView:mapView viewForAnnotation:(RouteAnnotation*)annotation];
    }
    if(index==1){
        
        self.annotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"myAnnotation"];
        
        self.annotationView.pinColor = BMKPinAnnotationColorPurple;
        
        self.annotationView.animatesDrop = YES;// 设置该标注点动画显示
        
        self.annotationView.annotation=annotation;
        self.annotationView.image = [UIImage imageNamed:@"3pic_icon01.png"];   //把大头针换成别的图片
        // 获取状态  （当前状态）
        if ([self.userOrTourist isEqualToString:@"1"]) {
            [self getAlarmStatus];
        }

        paopao=[[UIImageView alloc]init];
        
        paopaoLab_time=[[UILabel alloc]initWithFrame:CGRectMake(10, 10, 205, 15)];
        paopaoLab_time.text=@"定位时间:";
        paopaoLab_time.font=[UIFont systemFontOfSize:14];
        paopaoLab_time.textColor=[UIColor whiteColor];
        paopaoLab_time.textAlignment=NSTextAlignmentLeft;
        [paopao addSubview:paopaoLab_time];
        
        paopaoLab_phone=[[UILabel alloc]initWithFrame:CGRectMake(10, 30, 160, 15)];
        paopaoLab_phone.text=@"告警号码:";
        paopaoLab_phone.font=[UIFont systemFontOfSize:14];
        paopaoLab_phone.textColor=[UIColor whiteColor];
        paopaoLab_phone.textAlignment=NSTextAlignmentLeft;
        [paopao addSubview:paopaoLab_phone];
        
        paopaoLab_status = [[UILabel alloc]initWithFrame:CGRectMake(10, 50, 200, 15)];
        paopaoLab_status.text = @"当前状态:";
        paopaoLab_status.font = [UIFont systemFontOfSize:14];
        paopaoLab_status.textColor = [UIColor whiteColor];
        paopaoLab_status.textAlignment = NSTextAlignmentLeft;
        [paopao addSubview:paopaoLab_status];
        
        paopaoLab_loc=[[UILabel alloc]initWithFrame:CGRectMake(10, 70, 160, 15)];
        paopaoLab_loc.numberOfLines=0;
        NSString *loctext=@"当前位置:2015-08-01000000000000000000000000000000000";
        CGSize size=CGSizeMake(160, 0);
        NSDictionary *fontdic=@{NSFontAttributeName:[UIFont systemFontOfSize:14]};
        CGFloat h=[self celheight:loctext andtextsize:size andfontdic:fontdic];
        paopaoLab_loc.text=loctext;
        paopaoLab_loc.font=[UIFont systemFontOfSize:14];
        paopaoLab_loc.textColor=[UIColor whiteColor];
        paopaoLab_loc.textAlignment=NSTextAlignmentLeft;
        paopaoLab_loc.frame=CGRectMake(10, 50, 160, h);
        [paopao addSubview:paopaoLab_loc];
        
        paopao.image=[UIImage imageNamed:@"3pic_black"];
        
        
//        paopao.backgroundColor = [UIColor colorWithWhite:0.8 alpha:1];
        self.annotationView.paopaoView=[[BMKActionPaopaoView alloc]initWithCustomView:paopao];
        return self.annotationView;
    }
//    当锚点定位的时候进行大头针自定义操作

    BMKPinAnnotationView *newAnnotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"myAnnotation"];
    
    paopao2=[[UIImageView alloc]init];
    paopao2.image=[UIImage imageNamed:@"3pic_black"];
    
    
//    paopaoLab_loc.text=[lab_address stringByAppendingString:address];
//    CGSize size=CGSizeMake(200, 0);
//    NSDictionary *fontdic=@{NSFontAttributeName:[UIFont systemFontOfSize:14]};
//    CGFloat h=[self celheight:paopaoLab_loc.text andtextsize:size andfontdic:fontdic];
//    paopaoLab_loc.frame=CGRectMake(10, 70, 200, h);
    
  

    
    
    paopao2.frame=CGRectMake(0, 0, 130, 35);
    newAnnotationView.paopaoView=[[BMKActionPaopaoView alloc]initWithCustomView:paopao2];

    
    newAnnotationView.pinColor = BMKPinAnnotationColorPurple;
    
    newAnnotationView.animatesDrop = YES;// 设置该标注点动画显示
    
    newAnnotationView.annotation=annotation;
    
    //newAnnotationView.image = [UIImage imageNamed:@"anchor_icon.png"];
    // time  date chang meachine
    double timeinterv=[[array_historyPositions[count] objectForKey:@"posdate"]doubleValue];
    

    NSDate *date=[NSDate dateWithTimeIntervalSince1970:timeinterv/1000];
    NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
    [formatter setDateFormat:@" yyyy-MM-dd HH:mm"];
    NSString *text=[formatter stringFromDate:date];
    UILabel *lab=[[UILabel alloc]initWithFrame:CGRectMake(0, -8, 125, 50)];
    lab.font=[UIFont systemFontOfSize:13];
    lab.textColor=[UIColor whiteColor];
    lab.textAlignment=NSTextAlignmentCenter;
    lab.text=text;



    [paopao2 addSubview:lab];

    
    newAnnotationView.image = [self usePostDateToGetImage:timeinterv];
    
    return newAnnotationView;
}


- (void)tapped_changeremarktype{
    self.tabBarController.tabBar.userInteractionEnabled=NO;
    back=YES;
    backView=[[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    backView.backgroundColor=[UIColor colorWithWhite:0.2 alpha:0.5];
    
    alertimage=[[UIImageView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH-40*W-150, SCREEN_HEIGHT-49-140*W, 150, 75)];
    
    alertimage.image=[UIImage imageNamed:@"7pic_bounced"];
    alertimage.userInteractionEnabled=YES;
    btn_maodian=[[RemarkButton alloc]initWithFrame:CGRectMake(15, 7, 50, 60)];
    [btn_maodian setImage:[UIImage imageNamed:@"7pic_icon01"] forState:UIControlStateNormal];

    if(tag_remark==1){
        [btn_maodian setBackgroundImage:[UIImage imageNamed:@"7pic_selected"] forState:UIControlStateNormal];
    }
    else{
        [btn_maodian setBackgroundImage:[UIImage imageNamed:@"7pic_selected02"] forState:UIControlStateNormal];
    }
    [btn_maodian addTarget:self action:@selector(tapped_maodian) forControlEvents:UIControlEventTouchUpInside];
    btn_maodian.titleLabel.font=[UIFont systemFontOfSize:11];
    btn_maodian.titleLabel.textAlignment=NSTextAlignmentCenter;
    [btn_maodian setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [btn_maodian setTitle:@"锚点定位" forState:UIControlStateNormal];
    [alertimage addSubview:btn_maodian];
    btn_guiji=[[RemarkButton alloc]initWithFrame:CGRectMake(75, 7, 50, 60)];
   
    [btn_guiji addTarget:self action:@selector(tapped_guiji) forControlEvents:UIControlEventTouchUpInside];
    [btn_guiji setImage:[UIImage imageNamed:@"7pic_icon02"] forState:UIControlStateNormal];
    if(tag_remark==1){
        [btn_guiji setBackgroundImage:[UIImage imageNamed:@"7pic_selected02"] forState:UIControlStateNormal];
    }
    else{
        [btn_guiji setBackgroundImage:[UIImage imageNamed:@"7pic_selected"] forState:UIControlStateNormal];
    }
    btn_guiji.titleLabel.font=[UIFont systemFontOfSize:11];
    btn_guiji.titleLabel.textAlignment=NSTextAlignmentCenter;
    [btn_guiji setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [btn_guiji setTitle:@"轨迹定位" forState:UIControlStateNormal];
    [alertimage addSubview:btn_guiji];
    
    btn_enlarge.enabled=NO;
    btn_reduce.enabled=NO;
    btn_remarktype.enabled=NO;
    btn_maptype.enabled=NO;
   // UIWindow *window1=[UIApplication sharedApplication].keyWindow;
    [self.view addSubview:backView];
    
    [self.view addSubview:alertimage];
}

- (void)tapped_guiji{
    [loadmsg loadImages];
    count_start=0;
    count_end=1;
    self.tabBarController.tabBar.userInteractionEnabled=YES;
    tag_remark=0;
    [backView removeFromSuperview];
    [alertimage removeFromSuperview];
    btn_enlarge.enabled=YES;
    btn_reduce.enabled=YES;
    btn_remarktype.enabled=YES;
    btn_maptype.enabled=YES;
    back=NO;
    NSArray* array = [NSArray arrayWithArray:mapView.annotations];
    [mapView removeAnnotations:array];
    NSArray* array1 = [NSArray arrayWithArray:mapView.overlays];
    [mapView removeOverlays:array1];
      NSLog(@"ggggagdgasd %ld",array_historyPositions.count);
    if(array_historyPositions.count>=2){
        
      
        
        [self donextforRemark];//坐标数大于等于2
    }
    else if(array_historyPositions.count==1){
        [self donextforRemarkonlyOnepoint];//坐标数为1
    }
    else{
        [loadmsg.imageview removeFromSuperview];
    }
}
#pragma mark 锚点描述进行操作
- (void)tapped_maodian{
    self.tabBarController.tabBar.userInteractionEnabled=YES;
//    进行tag值设置判断大头针的自定义
    tag_remark=1;
    [backView removeFromSuperview];
    [alertimage removeFromSuperview];
    btn_enlarge.enabled=YES;
    btn_reduce.enabled=YES;
    btn_remarktype.enabled=YES;
    btn_maptype.enabled=YES;
    back=NO;
    
    
    

    
    
    NSArray* array = [NSArray arrayWithArray:mapView.annotations];
    [mapView removeAnnotations:array];
    array = [NSArray arrayWithArray:mapView.overlays];
    [mapView removeOverlays:array];
    [self donextformaodianRemark];
}

- (void)tapped_changemaptype{
    //self.tabBarController.tabBarItem.enabled=NO;
    back=YES;
//    让tabbar不进行交互使用
    self.tabBarController.tabBar.userInteractionEnabled=NO;
    backView=[[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    backView.backgroundColor=[UIColor colorWithWhite:0.2 alpha:0.5];
    
    alertimage=[[UIImageView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH-40*W-150, SCREEN_HEIGHT-49-140*W, 150, 75)];
    
    alertimage.image=[UIImage imageNamed:@"7pic_bounced"];
    alertimage.userInteractionEnabled = YES;
    btn_commen=[[newButton alloc]initWithFrame:CGRectMake(15, 7, 50, 60)];
//    btn_commen.backgroundColor = [UIColor redColor];
    if(mapView.mapType==1){
        [btn_commen setImage:[UIImage imageNamed:@"8pic_standardmap_selcet"] forState:UIControlStateNormal];
    }
    else{
        [btn_commen setImage:[UIImage imageNamed:@"8pic_standardmap"] forState:UIControlStateNormal];
    }
    [btn_commen addTarget:self action:@selector(tapped_commen) forControlEvents:UIControlEventTouchUpInside];
    btn_commen.titleLabel.font=[UIFont systemFontOfSize:11];
    btn_commen.titleLabel.textAlignment=NSTextAlignmentCenter;
    [btn_commen setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [btn_commen setTitle:@"标准地图" forState:UIControlStateNormal];
    [alertimage addSubview:btn_commen];
    btn_weixing=[[newButton alloc]initWithFrame:CGRectMake(75, 7, 50, 60)];
    [btn_weixing addTarget:self action:@selector(tapped_weixing) forControlEvents:UIControlEventTouchUpInside];
    if(mapView.mapType==1){
        [btn_weixing setImage:[UIImage imageNamed:@"8pic_satellitemap"] forState:UIControlStateNormal];
    }
    else{
        [btn_weixing setImage:[UIImage imageNamed:@"8pic_satellitemap_select"] forState:UIControlStateNormal];
    }
    btn_weixing.titleLabel.font=[UIFont systemFontOfSize:11];
    btn_weixing.titleLabel.textAlignment=NSTextAlignmentCenter;
    [btn_weixing setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [btn_weixing setTitle:@"卫星地图" forState:UIControlStateNormal];
    [alertimage addSubview:btn_weixing];

    btn_enlarge.enabled=NO;
    btn_reduce.enabled=NO;
    btn_remarktype.enabled=NO;
    btn_maptype.enabled=NO;
    
    [self.view addSubview:backView];
    
    [self.view addSubview:alertimage];
    
}

- (void)tapped_commen{
    self.tabBarController.tabBar.userInteractionEnabled=YES;
    btn_enlarge.enabled=YES;
    btn_reduce.enabled=YES;
    btn_remarktype.enabled=YES;
    btn_maptype.enabled=YES;
    mapView.mapType=1;
    [backView removeFromSuperview];
    [alertimage removeFromSuperview];
    back=NO;
}

- (void)tapped_weixing{
    self.tabBarController.tabBar.userInteractionEnabled=YES;
    btn_enlarge.enabled=YES;
    btn_reduce.enabled=YES;
    btn_remarktype.enabled=YES;
    btn_maptype.enabled=YES;
    mapView.mapType=2;
    [backView removeFromSuperview];
    [alertimage removeFromSuperview];
    back=NO;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    
    if(back==YES){
        self.tabBarController.tabBar.userInteractionEnabled=YES;
        btn_enlarge.enabled=YES;
        btn_reduce.enabled=YES;
        btn_remarktype.enabled=YES;
        btn_maptype.enabled=YES;
        [backView removeFromSuperview];
        [alertimage removeFromSuperview];
        back=NO;
    }
    
}

- (void)currentLocation {
    
    NSLog(@"进入普通定位态");
//    [_locService startUserLocationService];
    
    mapView.showsUserLocation = NO;//先关闭显示的定位图层
    mapView.userTrackingMode = BMKUserTrackingModeNone;//设置定位的状态
    mapView.showsUserLocation = YES;//显示定位图层

}

- (void)didFailToLocateUserWithError:(NSError *)error
{
    NSLog(@"location error");
}

- (void)willStartLocatingUser
{
    NSLog(@"start locate");
}

- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    if ([self.userOrTourist isEqualToString:@"0"]) {
        NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
        CLLocationCoordinate2D coordinate;
        coordinate=(CLLocationCoordinate2D){userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude};
        
        mapView.centerCoordinate = coordinate;
        // 去掉蓝色的精度圈
        BMKLocationViewDisplayParam *displayParam = [[BMKLocationViewDisplayParam alloc]init];
        displayParam.isRotateAngleValid = true;//跟随态旋转角度是否生效
        displayParam.isAccuracyCircleShow = false;//精度圈是否显示
        displayParam.locationViewImgName= @"3pic_icon01";//定位图标名称
        displayParam.locationViewOffsetX = 0;//定位偏移量(经度)
        displayParam.locationViewOffsetY = 0;//定位偏移量（纬度）
        [mapView updateLocationViewWithParam:displayParam];
        [mapView updateLocationData:userLocation];
        
        anni=[[BMKPointAnnotation alloc]init];
        anni.coordinate=mapView.centerCoordinate;
        NSArray* array = [NSArray arrayWithArray:mapView.annotations];
        [mapView removeAnnotations:array];
        array = [NSArray arrayWithArray:mapView.overlays];
        [mapView removeOverlays:array];
        
        [mapView addAnnotation:anni];
        
        NSString *dateString = [self getCurrentTime];
        paopaoLab_time.text=[@"定位时间:" stringByAppendingString:dateString];
//        paopaoLab_phone.text=@"告警号码:";
//        paopaoLab_status.text = @"当前状态:";
        
        BMKReverseGeoCodeOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
        reverseGeocodeSearchOption.reverseGeoPoint = coordinate;
        BOOL flag = [search reverseGeoCode:reverseGeocodeSearchOption];
        if(flag)
        {
            NSLog(@"反geo检索发送成功");
        }
        else
        {
            NSLog(@"反geo检索发送失败");
        }
    }
    [_locService stopUserLocationService];
}

- (NSString *)getCurrentTime {

    NSDate *currentDate = [NSDate date];//获取当前时间，日期
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateString = [dateFormatter stringFromDate:currentDate];
    NSLog(@"dateString:%@",dateString);
    return dateString;
}

#pragma mark - 系统方法

- (void)viewWillAppear:(BOOL)animated{
    
    mapView.delegate = self;
    _locService = [[BMKLocationService alloc] init];
    _locService.delegate = self;
    mapView.showsUserLocation=YES;
    
//    反向地理编码实现。通过网络获取相应的各个轨迹点
    search=[[BMKGeoCodeSearch alloc]init];
    search.delegate=self;
    
    self.navigationController.navigationBar.hidden=YES;
    NSDictionary *dic=@{@"key":@"0"};
    [[NSNotificationCenter defaultCenter]postNotificationName:@"changetabbartwo" object:nil userInfo:dic];
    
    btn_enlarge.hidden=NO;
    btn_reduce.hidden=NO;
    btn_maptype.hidden=NO;
    if(index==1){
        if ([self.userOrTourist isEqualToString:@"1"]) {
            btn_remarktype.hidden=YES;
            [self dorequestForGetCurrentLoction];
            timer=[NSTimer scheduledTimerWithTimeInterval:reloadmaptime   target:self selector:@selector(dorequestForGetCurrentLoction3) userInfo:nil repeats:YES];
        }
        else {
            [_locService startUserLocationService];
            [self currentLocation];
        }
    }
    else{
        btn_remarktype.hidden=NO;
    }
}

- (void)viewWillDisappear:(BOOL)animated{
    btn_enlarge.enabled=YES;
    btn_reduce.enabled=YES;
    btn_remarktype.enabled=YES;
    btn_maptype.enabled=YES;
    [backView removeFromSuperview];
    [loadmsg.imageview removeFromSuperview];
    [alertimage removeFromSuperview];
    back=NO;
    btn_enlarge.hidden=YES;
    btn_reduce.hidden=YES;
    btn_maptype.hidden=YES;
    btn_remarktype.hidden=YES;
    _locService.delegate = nil;
    mapView.delegate = nil; // 不用时，置nil
    search.delegate = nil;
    [timer invalidate];

}


- (CGFloat)celheight :(NSString *)str andtextsize:(CGSize) textsize andfontdic:(NSDictionary *)dic
{
    
    CGRect rect=[str boundingRectWithSize:textsize options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:dic context:nil];
    return rect.size.height;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController{
    [[NSUserDefaults standardUserDefaults]setObject:@"1" forKey:@"yiwan"];
}


@end
